package com.hndzyu.yd.customtask;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.Html;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.gson.Gson;
import com.gyf.barlibrary.ImmersionBar;
import com.hndzyu.yd.R;
import com.hndzyu.yd.bean.Card;
import com.hndzyu.yd.bean.ScreenTaskBean;
import com.hndzyu.yd.bean.UserBean;
import com.hndzyu.yd.pay.PayVIPActivity;
import com.hndzyu.yd.task.WebActivity;
import com.hndzyu.yd.url.Path;
import com.hndzyu.yd.utils.OkHttpDownloadJsonUtil;
import com.hndzyu.yd.utils.SharedPreferencesUtils;
import com.hndzyu.yd.utils.Util;
import com.hndzyu.yd.widget.CountdownTextView;
import com.hndzyu.yd.widget.ExitDialog;
import com.hndzyu.yd.widget.MyGridView;
import com.hndzyu.yd.widget.VipDIalog;


import org.json.JSONException;
import org.json.JSONObject;
import org.xml.sax.XMLReader;

import java.util.Arrays;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.wcy.htmltext.HtmlImageLoader;
import me.wcy.htmltext.HtmlText;
import me.wcy.htmltext.OnTagClickListener;

public class ScreenTaskDetailsActivity extends AppCompatActivity {

    @BindView(R.id.top_title)
    TextView topTitle;
    @BindView(R.id.tv_text)
    TextView tvText;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.tv_num)
    TextView tvNum;
    @BindView(R.id.tv_content)
    TextView tvContent;
    @BindView(R.id.gridView)
    MyGridView gridView;
    @BindView(R.id.tv_commit)
    TextView tvCommit;
    @BindView(R.id.tv_type)
    TextView tvType;
    @BindView(R.id.tv_day)
    TextView tvDay;
    @BindView(R.id.tv_quxiao)
    TextView tvQuxiao;
    @BindView(R.id.tv_time)
    CountdownTextView tvTime;
    @BindView(R.id.ll_shangchuan)
    LinearLayout llShangchuan;
    @BindView(R.id.ll_jinxing)
    LinearLayout llJinxing;
    @BindView(R.id.tv_chakan)
    TextView tvChakan;
    @BindView(R.id.iv_chakan)
    ImageView ivChakan;
    @BindView(R.id.tv_status)
    TextView tvstatus;
    @BindView(R.id.iv_isvip)
    ImageView iv_isvip;
    @BindView(R.id.gourl)
    TextView gourl;
    @BindView(R.id.iv_img)
    ImageView iv_img;
    @BindView(R.id.tv_vip)
    TextView tv_vip;

    //private ScreenBean.DataBeanX.DataBean item;
    private int taskid = 0;
    private int again = 0; //1确定放弃上个任务
    private ScreenTaskBean bean;
    private int type = 3;
    private int Detailtype = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_screen_task_details);
        ButterKnife.bind(this);
        ImmersionBar.with(this).fitsSystemWindows(true).statusBarColor(R.color.colorAccent).init();
        taskid = getIntent().getIntExtra("taskid", 0);
        //item = (ScreenBean.DataBeanX.DataBean) getIntent().getExtras().getSerializable("item");
        type = getIntent().getIntExtra("type", 3);
        Detailtype = getIntent().getIntExtra("Detailtype", 0);
        initData();
    }

    Card card;

    private void initData() {
        topTitle.setText("任务详情");
        if (Detailtype == 4) {
            OkHttpDownloadJsonUtil.downloadJson(this, Path.CARD(UserBean.uid, taskid), new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
                @Override
                public void onsendJson(String json) {
                    Log.i("________", json);
                    gourl.setVisibility(View.VISIBLE);
                    Gson gson = new Gson();
                    card = gson.fromJson(json, Card.class);
                    tvText.setText(card.getData().getTitle());

                    tvType.setText("任务类型：信用卡");
                    tvDay.setVisibility(View.GONE);
                    tv_vip.setVisibility(View.VISIBLE);
                    isvip = card.getData().getIsvip();
                    if (UserBean.level==0){
                        tv_vip.setText(card.getJin()+"元");
                        tvMoney.setText(Util.Sub(card.getJin()/Double.parseDouble(UserBean.vipcarddivide)*Double.parseDouble(UserBean.carddivide)+"")+ "元");
                    }else {
                        tv_vip.setText(card.getJin()+"元");
                        tvMoney.setText(Util.Sub(card.getJin()/Double.parseDouble(UserBean.vipcarddivide)*Double.parseDouble(UserBean.carddivide)+"")+ "元");
                    }
                    if (isvip == 1) {
                        iv_isvip.setVisibility(View.VISIBLE);
                    } else {
                        iv_isvip.setVisibility(View.GONE);
                    }
                    Glide.with(ScreenTaskDetailsActivity.this).load(Path.img(card.getData().getLogo())).apply(new RequestOptions().error(R.mipmap.logo)).into(iv_img);
                    String content = card.getData().getScon().replace("src=\"", "src=\"http://zhuanxiaobao.com");
                    gourl.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Intent intent = new Intent(ScreenTaskDetailsActivity.this, WebActivity.class);
                            intent.putExtra("url", card.getData().getUrl());
                            intent.putExtra("fen", "");
                            startActivity(intent);
                        }
                    });
                    tvContent.setMovementMethod(LinkMovementMethod.getInstance());
                    HtmlText.from(content)
                            .setImageLoader(new HtmlImageLoader() {

                                @Override
                                public void loadImage(String url, final Callback callback) {
                                    // Glide sample, you can also use other image loader
                                    Glide.with(getApplicationContext()).asBitmap()
                                            .load(url)
                                            .into(new SimpleTarget<Bitmap>() {
                                                @Override
                                                public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                                                    callback.onLoadComplete(resource);
                                                }
                                            });
                                }

                                @Override
                                public Drawable getDefaultDrawable() {
                                    return ContextCompat.getDrawable(getApplicationContext(), R.mipmap.ic_launcher);
                                }

                                @Override
                                public Drawable getErrorDrawable() {
                                    return ContextCompat.getDrawable(getApplicationContext(), R.mipmap.ic_launcher);
                                }

                                @Override
                                public int getMaxWidth() {
                                    return Util.getScreenWidth(getApplicationContext());
                                }

                                @Override
                                public boolean fitWidth() {
                                    return false;
                                }
                            })
                            .setOnTagClickListener(new OnTagClickListener() {
                                @Override
                                public void onImageClick(Context context, List<String> imageUrlList, int position) {
                                    ivChakan.setVisibility(View.VISIBLE);
                                    Glide.with(ScreenTaskDetailsActivity.this).load(imageUrlList.get(position)).into(ivChakan);
                                }

                                @Override
                                public void onLinkClick(Context context, String url) {
                                    // link click
                                }
                            }).into(tvContent);

                    //                    else if (type == 3) {
//                        //5未领取任务   0已领取   1已提交
                    switch (card.getStatus()) {
                        case 5:
                            tvCommit.setVisibility(View.GONE);
                            llJinxing.setVisibility(View.VISIBLE);
                            tvChakan.setVisibility(View.GONE);
                            tvQuxiao.setVisibility(View.GONE);
                            tvTime.setVisibility(View.GONE);
//                                }
                            break;
                        case 0:
                        case 1:
                        case 2:
                        case 3:
                            tvCommit.setVisibility(View.GONE);
                            llJinxing.setVisibility(View.GONE);
                            tvChakan.setVisibility(View.VISIBLE);
                            break;


                    }
                }
            });
        } else

        {
            subTaskDetail(taskid, UserBean.uid);
        }
    }

    @OnClick({R.id.top_back, R.id.tv_commit, R.id.tv_quxiao, R.id.ll_shangchuan, R.id.tv_chakan, R.id.iv_chakan})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.top_back:
                finish();
                break;
            case R.id.tv_commit:
                //申请任务
                claimTask(UserBean.uid, taskid);
                break;
            case R.id.tv_quxiao:
                //取消任务
                cancelTask(UserBean.uid, taskid);
                break;
            case R.id.ll_shangchuan:
                if (Detailtype == 4) {
                    if (isvip == 1) {
                        if (UserBean.level == 0) {
                            final VipDIalog vipDIalog = new VipDIalog(ScreenTaskDetailsActivity.this);
                            vipDIalog.setVIPListener(new VipDIalog.VIPListener() {
                                @Override
                                public void chooseTrue() {
                                    if (UserBean.gao > 0) {
                                        startActivity(new Intent(ScreenTaskDetailsActivity.this, PayVIPActivity.class));
                                    } else {
                                        Toast.makeText(ScreenTaskDetailsActivity.this, "首次提现方能开通", Toast.LENGTH_SHORT).show();
                                    }
                                    vipDIalog.dismiss();
                                }

                                @Override
                                public void chooseFalse() {
                                    vipDIalog.dismiss();

                                }
                            });
                            vipDIalog.show();
                            vipDIalog.setContent();
                        } else {
                            startActivityForResult(new Intent(this, PictureUploadActivity.class).putExtra("taskid", taskid)
                                    .putExtra("examplepic", ""), 110);
                        }
                    } else {
                        startActivityForResult(new Intent(this, PictureUploadActivity.class).putExtra("taskid", taskid)
                                .putExtra("examplepic", ""), 110);
                    }

                } else {
                    startActivityForResult(new Intent(this, PictureUploadActivity.class).putExtra("taskid", taskid)
                            .putExtra("examplepic", bean.getData().getExamplepic()), 110);
                }
                break;
            case R.id.tv_chakan:
                Intent intent = new Intent(this, PictureUploadDetailsActivity.class);
                Bundle bundle = new Bundle();
                if (Detailtype == 4) {
                    bundle.putSerializable("item", new ScreenTaskBean(new ScreenTaskBean.DataBean(card.getData().getTaskid(), card.getData().getTitle(), 0, card.getData().getIsvip()), -1, card.getJin()));
                } else {
                    bundle.putSerializable("item", bean);
                }
                intent.putExtras(bundle);
                startActivity(intent);
                break;
            case R.id.iv_chakan:
                ivChakan.setVisibility(View.GONE);
        }
    }

    private int isvip = 0;

    //获取任务详情
    private void subTaskDetail(final int taskid, int uid) {
        OkHttpDownloadJsonUtil.downloadJson(this, Path.subTaskDetail + "?taskid=" + taskid + "&uid=" + uid,
                new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
                    @Override
                    public void onsendJson(String json) {
                        if (!"1".equals(json) && !"2".equals(json)) {
                            Gson gson = new Gson();
                            bean = gson.fromJson(json, ScreenTaskBean.class);
                            isvip = bean.getData().getIsvip();
                            if (isvip == 1) {
                                iv_isvip.setVisibility(View.VISIBLE);
                            } else {
                                iv_isvip.setVisibility(View.GONE);
                            }
                            tvText.setText(bean.getData().getTname());
                            tvMoney.setText(bean.getJin() + "元");
                            tvNum.setText("剩余" + bean.getNum() + "份");
                            //1下载  2注册  3其他
                            switch (bean.getData().getType()) {
                                case 1:
                                    tvType.setText("任务类型：下载");
                                    break;
                                case 2:
                                    tvType.setText("任务类型：注册");
                                    break;
                                case 3:
                                    tvType.setText("任务类型：其他");
                                    break;
                            }
                            tvDay.setText("到期时间：" + Util.stampToDate(bean.getData().getRuntime() + ""));
                            tvContent.setText(bean.getData().getTcontent());
                            List<String> url = Arrays.asList(bean.getData().getExamplepic().split(","));
                            gridView.setAdapter(new ImageAdapter(ScreenTaskDetailsActivity.this, url));
                            Log.d("sdsjfhs", bean.getStatus() + "");
                            if (type == 0) {
                                tvstatus.setVisibility(View.VISIBLE);
                                tvstatus.setText("待审核");
                            } else if (type == 1) {
                                tvstatus.setVisibility(View.VISIBLE);
                                tvstatus.setText("审核列表");
                                tvstatus.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        startActivity(new Intent(ScreenTaskDetailsActivity.this, TaskidGetChecksActivity.class).putExtra("taskid", taskid));
                                    }
                                });
                            } else if (type == 2) {
                                tvstatus.setVisibility(View.VISIBLE);
                                tvstatus.setText("审核未通过");
                            } else if (type == 3) {
                                //5未领取任务   0已领取   1已提交
                                switch (bean.getStatus()) {
                                    case 5:
                                        if (bean.getNum() == 0) {
                                            Toast.makeText(ScreenTaskDetailsActivity.this, "任务已经领完啦！", Toast.LENGTH_SHORT).show();
                                        } else {
                                            tvCommit.setVisibility(View.VISIBLE);
                                            llJinxing.setVisibility(View.GONE);
                                            tvChakan.setVisibility(View.GONE);
                                        }
                                        break;
                                    case 0:
                                        long endtime = Long.parseLong((String) SharedPreferencesUtils.getParam(ScreenTaskDetailsActivity.this, "timer", ""));
                                        long time = endtime - System.currentTimeMillis() / 1000;
                                        tvTime.init("过期倒计时:%s", time);
                                        tvTime.start(0);
                                        llJinxing.setVisibility(View.VISIBLE);
                                        tvCommit.setVisibility(View.GONE);
                                        tvChakan.setVisibility(View.GONE);
                                        break;
                                    case 1:
                                        tvCommit.setVisibility(View.GONE);
                                        llJinxing.setVisibility(View.GONE);
                                        tvChakan.setVisibility(View.VISIBLE);
                                        break;
                                    case 4:
                                        tvCommit.setVisibility(View.GONE);
                                        llJinxing.setVisibility(View.GONE);
                                        tvChakan.setVisibility(View.GONE);
                                        break;
                                    default:
                                        tvCommit.setVisibility(View.GONE);
                                        llJinxing.setVisibility(View.GONE);
                                        tvChakan.setVisibility(View.VISIBLE);
                                        break;
                                }
                            }

                        } else {
                            Toast.makeText(ScreenTaskDetailsActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    //领取任务
    private void claimTask(int uid, final int taskid) {
        if (isvip == 1) {
            if (UserBean.level == 0) {
                final VipDIalog vipDIalog = new VipDIalog(ScreenTaskDetailsActivity.this);
                vipDIalog.setVIPListener(new VipDIalog.VIPListener() {
                    @Override
                    public void chooseTrue() {
                        if (UserBean.gao > 0) {
                            startActivity(new Intent(ScreenTaskDetailsActivity.this, PayVIPActivity.class));
                        } else {
                            Toast.makeText(ScreenTaskDetailsActivity.this, "首次提现方能开通", Toast.LENGTH_SHORT).show();
                        }
                        vipDIalog.dismiss();
                    }

                    @Override
                    public void chooseFalse() {
                        vipDIalog.dismiss();

                    }
                });
                vipDIalog.show();
                vipDIalog.setContent();
            }else {
                OkHttpDownloadJsonUtil.downloadJson(this, Path.claimTask + "?uid=" + uid + "&taskid=" + taskid,
                        new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
                            @Override
                            public void onsendJson(String json) {
                                if (!"1".equals(json) && !"2".equals(json)) {
                                    try {
                                        JSONObject jsonObject = new JSONObject(json);
                                        if (jsonObject.has("status")) {
                                            if (jsonObject.getInt("status") == 1) {
                                                Toast.makeText(ScreenTaskDetailsActivity.this, jsonObject.getString("info"), Toast.LENGTH_SHORT).show();
                                                subTaskDetail(taskid, UserBean.uid);
                                                SharedPreferencesUtils.setParam(ScreenTaskDetailsActivity.this, "timer", jsonObject.optInt("endtime") + "");
                                            } else {
                                                final ExitDialog mExitDialog = new ExitDialog(ScreenTaskDetailsActivity.this);
                                                mExitDialog.setExitListener(new ExitDialog.ExitListener() {
                                                    @Override
                                                    public void chooseTrue() {
                                                        //确定结束上个任务，开始当前任务
                                                        mExitDialog.dismiss();
                                                        again = 1;
                                                        cancelTask(UserBean.uid, taskid);
                                                    }

                                                    @Override
                                                    public void chooseFalse() {
                                                        //取消
                                                        mExitDialog.dismiss();
                                                    }
                                                });
                                                mExitDialog.show();
                                                mExitDialog.setTask(jsonObject.getString("info"));
                                            }
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                } else {
                                    Toast.makeText(ScreenTaskDetailsActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
            }
        } else {
            OkHttpDownloadJsonUtil.downloadJson(this, Path.claimTask + "?uid=" + uid + "&taskid=" + taskid,
                    new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
                        @Override
                        public void onsendJson(String json) {
                            if (!"1".equals(json) && !"2".equals(json)) {
                                try {
                                    JSONObject jsonObject = new JSONObject(json);
                                    if (jsonObject.has("status")) {
                                        if (jsonObject.getInt("status") == 1) {
                                            Toast.makeText(ScreenTaskDetailsActivity.this, jsonObject.getString("info"), Toast.LENGTH_SHORT).show();
                                            subTaskDetail(taskid, UserBean.uid);
                                            SharedPreferencesUtils.setParam(ScreenTaskDetailsActivity.this, "timer", jsonObject.optInt("endtime") + "");
                                        } else {
                                            final ExitDialog mExitDialog = new ExitDialog(ScreenTaskDetailsActivity.this);
                                            mExitDialog.setExitListener(new ExitDialog.ExitListener() {
                                                @Override
                                                public void chooseTrue() {
                                                    //确定结束上个任务，开始当前任务
                                                    mExitDialog.dismiss();
                                                    again = 1;
                                                    cancelTask(UserBean.uid, taskid);
                                                }

                                                @Override
                                                public void chooseFalse() {
                                                    //取消
                                                    mExitDialog.dismiss();
                                                }
                                            });
                                            mExitDialog.show();
                                            mExitDialog.setTask(jsonObject.getString("info"));
                                        }
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            } else {
                                Toast.makeText(ScreenTaskDetailsActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
        }
    }

    //取消任务
    private void cancelTask(int uid, final int taskid) {
        OkHttpDownloadJsonUtil.downloadJson(this, Path.cancelTask + "?uid=" + uid + "&taskid=" + taskid,
                new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
                    @Override
                    public void onsendJson(String json) {
                        if (!"1".equals(json) && !"2".equals(json)) {
                            try {
                                JSONObject jsonObject = new JSONObject(json);
                                if (jsonObject.has("status")) {
                                    Toast.makeText(ScreenTaskDetailsActivity.this, jsonObject.getString("info"), Toast.LENGTH_SHORT).show();
                                    if (jsonObject.getInt("status") == 1) {
                                        if (again == 1) {
                                            claimTask(UserBean.uid, taskid);
                                        } else {
                                            subTaskDetail(taskid, UserBean.uid);
                                        }
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        } else {
                            Toast.makeText(ScreenTaskDetailsActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    class ImageAdapter extends BaseAdapter {
        private List<String> datas;
        private Context mContext;

        public ImageAdapter(Context mContext, List<String> datas) {
            this.mContext = mContext;
            this.datas = datas;
        }

        @Override
        public int getCount() {
            return datas.size();
        }

        @Override
        public Object getItem(int i) {
            return datas.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(final int i, View view, ViewGroup viewGroup) {
            ViewHolder vh;
            if (view == null) {
                vh = new ViewHolder();
                view = LayoutInflater.from(mContext).inflate(R.layout.item_source_image, null);
                vh.ivImage = (ImageView) view.findViewById(R.id.iv_img);
                view.setTag(vh);
            } else {
                vh = (ViewHolder) view.getTag();
            }
            Glide.with(mContext).load(Path.BASE_URL + datas.get(i)).into(vh.ivImage);
            vh.ivImage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    ivChakan.setVisibility(View.VISIBLE);
                    Glide.with(mContext).load(Path.BASE_URL + datas.get(i)).into(ivChakan);
                }
            });
            return view;
        }

        class ViewHolder {
            public ImageView ivImage;
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        initData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ImmersionBar.with(this).destroy();
    }

    public class URLTagHandler implements Html.TagHandler {

        private Context mContext;

        public URLTagHandler(Context context) {
            mContext = context.getApplicationContext();
        }

        @Override
        public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) {
            // 处理标签<img>
            if (tag.toLowerCase(Locale.getDefault()).equals("img")) {
                // 获取长度
                int len = output.length();
                // 获取图片地址
                ImageSpan[] images = output.getSpans(len - 1, len, ImageSpan.class);
                String imgURL = images[0].getSource();
                // 使图片可点击并监听点击事件
                output.setSpan(new ClickableImage(mContext, imgURL), len - 1, len, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
    }

    private class ClickableImage extends ClickableSpan {
        private String url;
        private Context context;

        public ClickableImage(Context context, String url) {
            this.context = context;
            this.url = url;
        }

        @Override
        public void onClick(View widget) {
            // 进行图片点击之后的处理
            Toast.makeText(context, "放大", Toast.LENGTH_SHORT).show();
        }
    }

}
